package com.easy.controller;

import com.alibaba.excel.EasyExcel;
import com.easy.bean.User;
import com.easy.common.CommonResult;
import com.easy.config.EasyConfig;
import com.easy.dao.IUserDao;
import com.easy.excel.EasyObjExcelListener;
import com.easy.service.IUserService;
import com.easy.util.JWTUtil;
import com.easy.util.Page;
import com.easy.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class UserController {
    @Autowired
    IUserDao dao;

    @Autowired
    IUserService userService;

    private static String checkCode;

//    @RequestMapping("hello")
//    public String hello(){
//        return "java so easy";
//    }
//
//    @GetMapping("now")
//    public String now() {
//        return dao.getNow();
//    }

    //通过ID获取用户
    @GetMapping("user/{id}")
    public CommonResult getUserByID(@PathVariable int id) {
        User user = dao.getUserByID(id);
        return CommonResult.success(200,"ID查找成功",user);
    }

    //获取用户列表
    @GetMapping("user")
    @Transactional
    public CommonResult getUser(User user, Page page) {
        List<User> list =userService.getUser(user,page);
        int count=userService.getCount(user);
        HashMap map=new HashMap();
        map.put("list",list);
        map.put("count",count);
        return CommonResult.success(map);
    }

    //删除用户
    @DeleteMapping("user/{id}")
    public CommonResult delUser(@PathVariable int id) {
        int count = userService.delUser(id);
        if(count>0){
            return CommonResult.success(count);
        }else {
            return CommonResult.fail();
        }

    }

    //新增用户form
    @PostMapping("user")
    public CommonResult addUser(User user){
        List<User> list = userService.getUserByUserName(user.getUsername());
        if(list.size()>0){
            return CommonResult.fail(400,"用户已存在",list);
        }else {
            userService.addUser(user);
            user = userService.getUserByID(user.getId());
            return CommonResult.success(user);
        }
    }

    //新增用户JSON
    @PostMapping("userjson")
    @Transactional
    public CommonResult addUserJSON(@RequestBody User user){
        List<User> list = userService.getUserByUserName(user.getUsername());
        if(list.size()>0){
            return CommonResult.fail(400,"用户已存在",list);
        }else {
            userService.addUser(user);
            user = userService.getUserByID(user.getId());
            return CommonResult.success(400,"添加成功",user);
        }

    }

    //修改用户
    @PutMapping("userjson")
    @Transactional
    public CommonResult editUserJSON(@RequestBody User user) {
        userService.editUser(user);
        user = userService.getUserByID(user.getId());
        return CommonResult.success(user);
    }

    //登录
    @PostMapping("dologin")
    @Transactional
    public CommonResult doLogin(User user, String checkCode, HttpServletRequest request){

        // 从Session中获取验证码
        String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
        System.out.println(sessionCaptcha+"-----");
        if (sessionCaptcha == null || !sessionCaptcha.equals(checkCode)) {
            System.out.println(checkCode + "-----验证失败");
            return CommonResult.fail(405, "验证码不正确");
        }
        // 清除Session中的验证码
        request.getSession().removeAttribute("captcha");

        String token=userService.doLogin(user);
        if(token==null){
            return CommonResult.fail(403,"登录失败");
        }else {
            List<User> list =userService.getUserByUserName(user.getUsername());
                System.out.println(sessionCaptcha +"-----登录");
                HashMap map=new HashMap();
                if(list.size()>0){
                    int id =list.get(0).getId();
                    map.put("id",id);
                    map.put("token",token);
                }
                return CommonResult.success(200, "登录成功", map);
            }

        }

    @PostMapping("checkpass")
    @Transactional
    public CommonResult doCheckPass(User user, String checkCode){
        String token=userService.doLogin(user);
        if(token==null){
            return CommonResult.fail(403,"验证失败");
        }else {
            List<User> list =userService.getUserByUserName(user.getUsername());
            HashMap map=new HashMap();
            if(list.size()>0){
                int id =list.get(0).getId();
                map.put("id",id);
                map.put("token",token);
            }
            return CommonResult.success(200, "验证成功", map);
        }

    }

    @GetMapping("checktoken")
    public CommonResult checkToken(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if(token!=null && JWTUtil.verifyToken(token)){
            Map<String, Object> map = JWTUtil.decodeJWT(token);
            return CommonResult.success(200,"解析成功",map);

        }
        return CommonResult.fail();
    }

    //注册
    @PostMapping("register")
    @Transactional
    public CommonResult register(@RequestBody User user){
        if(user.getUsername()!=null && user.getPassword()!=null){
            List<User> list = userService.getUserByUserName(user.getUsername());
            if(list.size()>0){
                return CommonResult.fail(500,"用户已存在");
            }else {
                userService.addUser(user);
                user = userService.getUserByID(user.getId());
                user.setName("游客"+user.getId());
                userService.editUser(user);
                return CommonResult.success(200,"注册成功",user);
            }
        }else {
            return CommonResult.fail(403, "注册失败");
        }
    }

    @PostMapping("userimg")
    public CommonResult userImg(@RequestParam("file") MultipartFile file){
        //存储文件
        String newName = UploadFileUtil.uploadFile(file);
        //将文件地址存入数据库
        //返回上传文件的地址 / 返回上传头像的员工数据
        return CommonResult.success(EasyConfig.STATIC_PATH+newName);
    }

    @PutMapping("userimg")
    public CommonResult saveImg(User user){
        userService.saveImg(user);
        return CommonResult.success(200,"头像保存成功");
    }

    @PutMapping("setpass")
    public CommonResult setPass(User user){
        userService.setPassword(user);
        return CommonResult.success(200,"密码修改成功");
    }

    @PostMapping("userexcel")
    public CommonResult userExcel(@RequestParam("file")MultipartFile file){
        EasyObjExcelListener<User> userList= null;
        try{
            userList = new EasyObjExcelListener<User>();
            InputStream fis= null;
            try {
                fis = file.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            EasyExcel.read(fis,User.class,userList).sheet(0).doRead();
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.fail(400,"解析失败");
        }
//        for(User item : userList.list){
//            if(userService.getUserByUserName(item.getUsername()).size()>0){
//                System.out.println(item.getUsername()+"已存在");
//                continue;
//            }
//            userService.addUser(item);
//            System.out.println("新增用户："+item.toString());
//        }
        return CommonResult.success(200,"Excel导入成功",userList.list);

    }

    @PostMapping("checkcode")
    public CommonResult setCheckCode(String checkCode, HttpServletRequest request) {
        System.out.println(checkCode);
        // 将验证码存储在Session中
        request.getSession().setAttribute("captcha", checkCode);
        System.out.println(checkCode);
        return CommonResult.success(200, "验证码获取成功", checkCode);
    }
}
